package com.lin.sqltool.utils;



import com.lin.sqltool.beans.BaseBean;
import com.lin.sqltool.model.ConfigGroupModel;
import com.lin.sqltool.model.ConfigItemModel;
import com.lin.sqltool.model.ConnectionInfoModel;

import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.lin.sqltool.config.BaseConfig.*;

public class ConfigUtil {


    /**
     * 连接集合
     */
    private static final List<ConfigGroupModel> CONFIG_GROUP = new ArrayList<>();



    /**
     * 标志位，记录是否已经加载过连接配置
     */
    private static boolean isConfigLoaded = false;

    /**
     * 获取配置
     * @return
     */
    public static List<ConfigGroupModel> getConfigGroup() {
        if (!isConfigLoaded) {
            loadConnections();  //加载连接
        }
        return new ArrayList<>(CONFIG_GROUP);
    }



    /**
     * 保存配置到文件
     * @return
     */
    public static boolean saveConfig(){

        try {
            Files.createDirectories(SAVE_DIR);
            BaseBean.objectMapper.writeValue(CONFIG_FILE.toFile(), CONFIG_GROUP);
            return true;
        } catch (IOException e) {
            System.err.println("保存设置失败: " + e.getMessage());
            return false;
        }
    }

    /**
     * 加载配置
     * @return
     */
    public static boolean loadConnections() {

        try {
            if (CONFIG_FILE.toFile().exists()) {
                // 反序列化为 List<ConnectionModel>
                List<ConfigGroupModel> configGroupModels = BaseBean.objectMapper.readValue(
                        CONFIG_FILE.toFile(),
                        BaseBean.objectMapper.getTypeFactory().constructCollectionType(List.class, ConfigGroupModel.class)
                );
                CONFIG_GROUP.addAll(configGroupModels);
                return true;
            } else {
                CONFIG_GROUP.add(new ConfigGroupModel("基础", List.of(
                        new ConfigItemModel("模型", "", "select", "智普清言", "智普清言", List.of("智普清言")),
                        new ConfigItemModel("MODEL_NAME", "", "text", "", "GLM-4-Flash", null),
                        new ConfigItemModel("API_KEY", "", "text", "bc292732ee8a41fc946746371a13d44c", "", null)
                )));
            }
        } catch (IOException e) {
            System.err.println("加载配置失败: " + e.getMessage());

        }
        return false;
    }




}
